package com.fyl.processor;

import com.fyl.advice.MyAdvice;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class MockAopBeanPostProcessor implements BeanPostProcessor, ApplicationContextAware {
    private ApplicationContext applicationContext;
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        //目的：对serviceImpl中的show方法进行增强，增强方法在MyAdvice中
        //问题1：筛选 service.impl包下所有类的所有方法进行增强
        //问题2：从spring中获取MyAdvice怎么获取到？MyAdvice

        if(bean.getClass().getPackage().getName().equals("com.fyl.service.impl")){
            //生成当前bean的proxy对象
            Object proxy = Proxy.newProxyInstance(
                    bean.getClass().getClassLoader(),
                    bean.getClass().getInterfaces(),
                    new InvocationHandler() {
                        @Override
                        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                            MyAdvice myAdvice = applicationContext.getBean(MyAdvice.class);
                            //执行增强方法
                            myAdvice.beforeAdvice();
                            Object result = method.invoke(bean, args);
                            //执行增强方法
                            myAdvice.afterAdvice();
                            return result;
                        }
                    }
            );
            return proxy;
        }
        return bean;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
